﻿using MxWeiXinPF.Common;
using MxWeiXinPF.Common.log;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace MxWeiXinPF.BLL
{
   public   class WebApiPostUtils
    {
        /// <summary>
        /// 接口调用公共方法
        /// </summary>
        /// <param name="url">post的地址</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public static Model.WebApiResultData SendData(string url, string param)
        {
             
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            try
            {
                //string str = "{";
                ////反序列化JSON字符串  
                //JArray ja = (JArray)JsonConvert.DeserializeObject("[" + param + "]");
                //if (ja.Count > 0)
                //{
                //    //将反序列化的JSON字符串转换成对象  
                //    JObject o = (JObject)ja[0];
                //    foreach (var obj in o)
                //    {
                //        str += "\"" + obj.Key + "\":\"" + obj.Value + "\",";
                //    }
                //}

                //string ip = Utils.getIPAddress();
                //str += "\"platform\":\"muxueweixin\",\"IP\":\"" + ip + "\"}";
                //GZip压缩字符串参数
                string retStr = Utils.HttpPostByJson(url, param);
               
                if (!string.IsNullOrEmpty(retStr))
                {
                    retStr = retStr.Replace("\"{\\\"", "{\\\"").Replace("}\"", "}").Replace("\\\"", "\"");

                    if (!string.IsNullOrEmpty(retStr))
                    {
                        return retStr.ToObject<Model.WebApiResultData>();
                    }
                }
            }
            catch (Exception ex)
            {
                string _url = string.Format("{0}?{1}", url, param);
                
                LogHelper.Error("url=" + _url, ex);
                return new Model.WebApiResultData() { status = -1, detail = "网络繁忙，请稍后再试" };
            }

            return null;
        }


        /// <summary>
        /// 验证证书
        /// </summary>
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {

            return true;
        }


        /// <summary>
        /// 对应的webapi的功能模块
        /// </summary>
        public enum apiModule
        {
            //用户模块
            User,
            //消息模块
            Message,
            //字典模块
            Dictionary,
            //文章模块
            Article,
            //借款模块
            Loan,
            //还款模块
            Repayment,
            //银行模块
            Bank,
            //公共模块
            Common
        }



        /// <summary>
        /// 将传入的二进制字符串资料以GZip算法解压缩
        /// </summary>
        /// <param name="zippedString">经GZip压缩后的二进制字符串</param>
        /// <returns>原始未压缩字符串</returns>
        public static string GZipDecompressString(string zippedString)
        {
            if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0)
            {
                return "";
            }
            else
            {
                byte[] zippedData = Convert.FromBase64String(zippedString.ToString());
                return (string)(System.Text.Encoding.UTF8.GetString(Decompress(zippedData)));
            }
        }


        /// <summary>
        /// ZIP解压
        /// </summary>
        /// <param name="zippedData"></param>
        /// <returns></returns>
        public static byte[] Decompress(byte[] zippedData)
        {
            MemoryStream ms = new MemoryStream(zippedData);
            GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress);
            MemoryStream outBuffer = new MemoryStream();
            byte[] block = new byte[1024];
            while (true)
            {
                int bytesRead = compressedzipStream.Read(block, 0, block.Length);
                if (bytesRead <= 0)
                    break;
                else
                    outBuffer.Write(block, 0, bytesRead);
            }
            compressedzipStream.Close();
            return outBuffer.ToArray();
        }




        // <summary>
        /// Base64加密，解密方法
        /// </summary>
        /// <param name="s">输入字符串</param>
        /// <param name="c">true-加密,false-解密</param>
        public static byte[] GZipCompressString(string rawString, bool c)
        {
            if (c)
            {
                return Convert.FromBase64String(rawString.ToString());

            }
            else
            {
                byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString.ToString());
                return rawData;
            }
        }

        /// <summary>
        /// GZip压缩
        /// </summary>
        /// <param name="rawData"></param>
        /// <returns></returns>
        public static byte[] Compress(byte[] rawData)
        {
            MemoryStream ms = new MemoryStream();
            GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
            compressedzipStream.Write(rawData, 0, rawData.Length);
            compressedzipStream.Close();
            return ms.ToArray();
        }



        /// <summary>
        /// Base64加密，解密方法
        /// </summary>
        /// <param name="s">输入字符串</param>
        /// <param name="c">true-加密,false-解密</param>
        public static string base64(string s, bool c)
        {
            if (c)
            {
                return System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(s));
            }
            else
            {
                return System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(s));
            }
        }

    }
}
